/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package expenseslist;

import com.sun.xml.internal.ws.api.message.Message;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.freixas.jcalendar.DateEvent;
import org.freixas.jcalendar.DateListener;
import org.freixas.jcalendar.JCalendarCombo;

/**
 *
 * @author trunghpb
 */
public class ExpensesFrame extends JFrame{
    private static final int DEFAULT_WIDTH = 800;
    private static final int DEFAULT_HEIGHT = 200;
    DefaultTableModel model;
    
    public ExpensesFrame() {
        setTitle("Expense Frame");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        try{
            ExpenseDB expense = new ExpenseDB();
            ResultSet rs = expense.find();
  
            JPanel panelSearch = new JPanel();
            
            JCalendarCombo calendarDate = new JCalendarCombo(JCalendarCombo.DISPLAY_DATE, false);
            JLabel labelComboboxAccount = new JLabel("Account", SwingConstants.RIGHT);
            calendarDate.addDateListener(new ComboDateAction());
            panelSearch.add(labelComboboxAccount, BorderLayout.NORTH);
            
            AccountDB accountDb = new AccountDB();
            DbAdapter adapAccount = new DbAdapter();
            adapAccount.addString("account_name");
            adapAccount.addInt("account_id");
            accountList = adapAccount.getArray(accountDb.find());
            
            comboBoxAccount.addItem("All");
            for (int i = 0; i<accountList.length; i++){
                comboBoxAccount.addItem(accountList[i][0].toString());
            }
            comboBoxAccount.addActionListener(new AccountComboAction());
            panelSearch.add(comboBoxAccount, BorderLayout.NORTH);
            panelSearch.add(calendarDate, BorderLayout.NORTH);
            
            JButton addButton = new JButton("Add expense");            
            addButton.addActionListener(new ButtonAction());
            
            panelSearch.add(addButton, BorderLayout.SOUTH);
            add(panelSearch, BorderLayout.NORTH);
            
            DbAdapter adap = new DbAdapter();
            adap.addInt("expenses_id");
            adap.addString("expenses_name");
            adap.addDouble("expenses_amounth");
            adap.addDate("expenses_date");
            adap.addString("account_name");

            tableData = adap.getArray(rs);            
            model = new DefaultTableModel(tableData, columnNames);
            table = new JTable(model);
            
            TableColumn column = null;            
            for(int i = 0; i< NUMBER_COLUMN; i++){
                column = table.getColumnModel().getColumn(i);
                column.setPreferredWidth(columnWidth[i]);
            }

            table.setAutoCreateRowSorter(true);
            add(new JScrollPane(table), BorderLayout.CENTER);
            
        }catch (SQLException mye){
            JOptionPane.showMessageDialog(this, mye.getMessage());
        }catch (Exception e){
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }
    
    public void reloadExpenseList() throws Exception{
        ExpenseDB expense = new ExpenseDB();
        ResultSet rs = expense.find();

        refreshTable(rs);
    }
    
    private void refreshTable(ResultSet rs) throws SQLException{
        
        DbAdapter adap = new DbAdapter();
        adap.addInt("expenses_id");
        adap.addString("expenses_name");
        adap.addDouble("expenses_amounth");
        adap.addDate("expenses_date");
        adap.addString("account_name");

        tableData = adap.getArray(rs);
        model.setDataVector(tableData, columnNames);
        model.fireTableDataChanged();

        table.repaint();
    }
    
    class ButtonAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            AddExpensesFrame frame;
            try {
                frame = new AddExpensesFrame(ExpensesFrame.this);
                frame.setVisible(true);
            } catch (Exception ex) {
                Logger.getLogger(ExpensesFrame.class.getName()).log(Level.SEVERE, null, ex);
            }            
        }        
    }
    
    class AccountComboAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                ExpenseDB expense = new ExpenseDB();
                int iSelected = comboBoxAccount.getSelectedIndex();
                if (iSelected > 0){
                    expense.setAccount(new AccountDB(Integer.parseInt(accountList[iSelected-1][1].toString())));
                }
                ResultSet rs = expense.find();

                refreshTable(rs);
                
            } catch (Exception ex) {
                 Logger.getLogger(ExpensesFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }

    class ComboDateAction implements DateListener{

        public void dateChanged(DateEvent de) {
            Calendar cal = de.getSelectedDate();
            
            if (cal != null){
                try {
                    ExpenseDB expense = new ExpenseDB();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    expense.setDate(sdf.format(cal.getTime()));
                    
                    refreshTable(expense.find());
                } catch (Exception ex) {
                    Logger.getLogger(ExpensesFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        }
    
    }
    private String[] columnNames = {"Id", "Tên khoản", "Số tiền", "Ngày chi", "Tài khoản"};
    private int[] columnWidth = {50,600,150,120,300};
    
    private static final int NUMBER_COLUMN = 5;
    JTable table;
    Object[][] tableData;
    Object[][] accountList;
    
    JComboBox comboBoxAccount = new JComboBox();
}
